package com.company.cloud.crm.modules.mgr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.crm.modules.base.entity.CustomerLinkInfo;
import com.company.cloud.crm.modules.base.service.CustomerLinkInfoService;
import com.company.cloud.crm.modules.cache.models.LinkManModel;
import com.company.cloud.crm.modules.cache.utils.CrmBizChangeUtils;
import com.company.cloud.crm.modules.mgr.controller.req.LinkManQuery4PageParam;
import com.company.cloud.crm.modules.mgr.controller.req.LinkManSaveParam;
import com.company.cloud.crm.modules.mgr.controller.req.LinkManUpdateParam;
import com.company.cloud.crm.utils.CrmBizId;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@Authc
@RestController
@RequestMapping("/mgr/crm/linkMan")
@Api(tags = "CRM_Mgr_联系人管理")
public class CustomerLinkManMgrController {

    @Autowired
    private CustomerLinkInfoService customerLinkInfoService;

    @PostMapping("/query")
    @ApiOperation(value = "查询", response = LinkManModel.class)
    public BaseResult query(@RequestBody LinkManQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<CustomerLinkInfo> page = customerLinkInfoService.page(
                new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<CustomerLinkInfo>()
                        .eq("company_no", userInfo.getCompanyNo())
                        .eq(StringUtils.hasText(params.getCustNo()), "cust_no", params.getCustNo())
                        .eq(CheckUtils.hasInt(params.getSaleUserId()), "sale_user_id", params.getSaleUserId())
                        .eq(StringUtils.hasText(params.getState()), "state", params.getState())
                        .like(StringUtils.hasText(params.getName()), "name", params.getName())
                        .eq("rows_state", EnabledEnum.ENABLED.getCode())
        );
        IPage<LinkManModel> data = page.convert(new Function<CustomerLinkInfo, LinkManModel>() {
            @Override
            public LinkManModel apply(CustomerLinkInfo entity) {
                return CrmBizChangeUtils.getLinkMan(entity);
            }
        });
        return BaseResult.ok(data);
    }

    @GetMapping("/getListByCust")
    @ApiOperation(value = "根据客户获取联系人列表", response = LinkManModel.class)
    public BaseResult getListByCust(@RequestParam("custNo") String custNo) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        List<LinkManModel> data = this.getLinkManListByCust(userInfo.getCompanyNo(), custNo, null);
        return BaseResult.ok(data);
    }


    @GetMapping("/getListByCustByUser")
    @ApiOperation(value = "根据客户获取联系人列表(当前用户)", response = LinkManModel.class)
    public BaseResult getListByCustByUser(@RequestParam("custNo") String custNo) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        List<LinkManModel> data = this.getLinkManListByCust(userInfo.getCompanyNo(), custNo, userInfo.getId());
        return BaseResult.ok(data);
    }

    private List<LinkManModel> getLinkManListByCust(String companyNo, String custNo, Integer userId) {
        List<CustomerLinkInfo> linkList = customerLinkInfoService.list(new QueryWrapper<CustomerLinkInfo>()
                .eq("company_no", companyNo)
                .eq("cust_no", custNo)
                .eq(CheckUtils.hasInt(userId), "sale_user_id", userId)
                .eq("rows_state", EnabledEnum.ENABLED.getCode())
        );
        List<LinkManModel> data = new ArrayList<LinkManModel>();
        if (!CollectionUtils.isEmpty(linkList)) {
            linkList.forEach(entity -> {
                data.add(CrmBizChangeUtils.getLinkMan(entity));
            });
        }
        return data;
    }


    @PostMapping("/add")
    @ApiOperation(value = "新增", response = BaseResult.class)
    @StaffLogc(title = "新增联系人", action = "新增联系人", actionAdo = "联系人")
    public BaseResult add(@RequestBody LinkManSaveParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        CustomerLinkInfo entity = new CustomerLinkInfo();
        entity.setId(CrmBizId.getLinkManId());
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setCustNo(params.getCustNo());
        entity.setName(params.getName());
        entity.setDept(params.getDept());
        entity.setJob(params.getJob());
        entity.setSex(params.getSex());
        entity.setBirthday(params.getBirthday());
        entity.setIsDecisionMaker(params.getIsDecisionMaker());
        entity.setBizCardImg(params.getBizCardImg());
        entity.setIntroducer(params.getIntroducer());
        entity.setRemark(params.getRemark());
        entity.setTel(params.getTel());
        entity.setMobile(params.getMobile());
        entity.setFax(params.getFax());
        entity.setMail(params.getMail());
        entity.setState(params.getState());
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        customerLinkInfoService.save(entity);
        return BaseResult.ok();
    }


    @PostMapping("/edit")
    @ApiOperation(value = "修改", response = BaseResult.class)
    @StaffLogc(title = "修改联系人", action = "修改联系人", actionAdo = "联系人")
    public BaseResult edit(@RequestBody LinkManUpdateParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        CustomerLinkInfo entity = customerLinkInfoService.getById(params.getId());
        if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setName(params.getName());
        entity.setDept(params.getDept());
        entity.setJob(params.getJob());
        entity.setSex(params.getSex());
        entity.setBirthday(params.getBirthday());
        entity.setIsDecisionMaker(params.getIsDecisionMaker());
        entity.setBizCardImg(params.getBizCardImg());
        entity.setIntroducer(params.getIntroducer());
        entity.setRemark(params.getRemark());
        entity.setTel(params.getTel());
        entity.setMobile(params.getMobile());
        entity.setFax(params.getFax());
        entity.setMail(params.getMail());
        entity.setState(params.getState());
        entity.addEditParam(userInfo);
        customerLinkInfoService.updateById(entity);
        return BaseResult.ok();
    }

    @GetMapping("/get")
    @ApiOperation(value = "获取", response = LinkManModel.class)
    public BaseResult get(@RequestParam("id") String id) {
        CustomerLinkInfo entity = customerLinkInfoService.getById(id);
        if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LinkManModel data = CrmBizChangeUtils.getLinkMan(entity);
        return BaseResult.ok(data);
    }

    @GetMapping("/del")
    @ApiOperation(value = "删除", response = BaseResult.class)
    @StaffLogc(title = "删除联系人", action = "删除联系人", actionAdo = "联系人")
    public BaseResult del(@RequestParam("id") String id) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        CustomerLinkInfo entity = customerLinkInfoService.getById(id);
        if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setRowsState(EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        customerLinkInfoService.updateById(entity);
        return BaseResult.ok();
    }


}
